'''
Created on Dec 22, 2010

@author: Nican
'''

import os.path

class ValueSaver(object):
    '''
    classdocs
    '''


    def __init__(self, fileName):
        self.fileName = fileName
        self.Values = {}
        
    
    def readFromFile(self):
        self.Values = {}
        
        if not os.path.isfile(self.fileName):
            return
        
        with open(self.fileName, 'r') as f:
        
            for line in f:
                
                if line == "":
                    continue
                
                split = line.split("=", 1)
                
                if len(split) == 1:
                    continue
                
                key = split[0] 
                value = split[1][:-1]
                
                self.Values[ key ] = value
                
                print(key + " = " + value)
                
    def writeToFile(self):      
        with open(self.fileName, 'w') as f:
        
            for key, value in self.Values.iteritems():
                
                f.write(key + "=" + value + "\n")
              
            f.flush()
            
    def SetValue(self, key, value):
        self.Values[key] = value
        
        self.writeToFile()
        
    def GetValue(self, key, default = None):
        if key in self.Values:        
            return self.Values[key]
        return default
          

if __name__ == '__main__':
    test = ValueSafer('test.txt')
    
    test.SetValue("a", "123")
    test.SetValue("b", "456")
    
    test.writeToFile()
    test.readFromFile()
    
    if test.GetValue("a") != "123" or test.GetValue("b") != "456":
        print("Test for value safer failed!")
